#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
#获得 当前的地址
cur_dir=`pwd`

# Check if user is root
#判断用户是否是 root
if [ $(id -u) != "0" ]; then
    echo "必须是root用户才可以运行此脚本"
    exit 1
fi
# 判断网络是否畅通
ping -c 1 -t 1 www.baidu.com
if [[ $? == 2 ]];then
        echo "nameserver 8.8.8.8
nameserver 202.96.128.68" > /etc/resolv.conf
	echo "dns错误或者重启后安装"
	exit
fi

#错误显示 控制
function error_control(){
if [ $1 != 0 ];then
tail /root/oslamp_errors.log
distro=`cat /etc/issue`
architecture=`uname -m`
cat >>/root/oslamp_errors.log<<EOF
oslamp errors:
distributions:$distro
architecture:$architecture
issue:failed to install $2
EOF
echo "###########################################################"
echo "## failed to install $2--------安装错误                 ##"    
echo "## please visit http://www.baidu.com                     ##"
echo "## 或者找到以下文件 /root/oslamp_errors.log 寻求帮助     ##"
echo "###########################################################"
exit 1
fi
}

#下载文件的函数
#===============================================================================
#DESCRIPTION:download files.
#USAGE:download_files [filename] [secondary url] 
#===============================================================================
function download_files(){
if [ -s $1.tar.gz ]; then
  echo "$1 [found]"
  else
  echo "$1 not found!!!download now......"
 if ! wget -c --tries=3 http://soft123.qiniudn.com/linuxsoft/$1.tar.gz;then
 echo "Failed to download $1,please download it to "$cur_dir" directory manually and rerun the install script."
 exit 1
 fi
fi
}


#关闭selinux系统控制系统
function disable_selinux(){
if [ -s /etc/selinux/config ] && grep 'SELINUX=enforcing' /etc/selinux/config; then
	sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
	setenforce 0
fi
}

#stty时一个用来改变并打印终端行设置的常用命令（不懂）
get_char(){
	SAVEDSTTY=`stty -g`
	stty -echo
	stty cbreak
	dd if=/dev/tty bs=1 count=1 2> /dev/null
	stty -raw
	stty echo
	stty $SAVEDSTTY
}
	
#cpu 设置cpu核心数  使运行效率更高
function parallel_make(){
cpunum=`cat /proc/cpuinfo |grep 'processor'|wc -l`
make -j$cpunum
}

#安装前的配置
function pre_installation_settings(){
#设置 mysql密码
#1-set mysql root password
	echo "Please input the root password of mysql--请输入mysql的密码:"
	read -p "(Default password--默认root用户密码: root)默认请按确定:" mysqlrootpwd
	if [ "$mysqlrootpwd" = "" ]; then
		mysqlrootpwd="root"
	fi	
# echo "$mysqlrootpwd" >/root/my.cnf
echo "mysql password:$mysqlrootpwd"
echo "####################################"


#设置邮件服务的域名
#2-define the postfix domain.
echo "Please input the postfix domain--请输入邮件服务的域名(您网站的域名):"
	read -p "(域名格式为  aaa.com)默认请按确定:" postfixdomain
	[ "$postfixdomain" = "" ] && postfixdomain="aaa.com"
echo "postfix domain--邮件服务的域名:$postfixdomain"
echo "####################################"




echo ""
echo "Press any key to start...--请安任意键继续"
char=`get_char`

#关闭selinux系统控制系统
disable_selinux

#卸载 系统自带的apache php mysql	
rpm -e nginx
rpm -e mysql
rpm -e php


yum -y remove nginx
yum -y remove php
yum -y remove php-mysql


# 删除原有的时区链接
rm -rf /etc/localtime
#创建 新的时区链接
ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

#ntp 是网络自动更新时间
#安装 自动对时工具
yum install -y ntp
ntpdate tiger.sina.com.cn
hwclock -w
#显示当前时间
date
sleep 2
#获得当前系统bit位
if [ `uname -m | grep "x86_64"` ];then
	X64="1"
fi

#安装 一些 必须的工具
if [ ! -f /tmp/yum_installed ];then
yum install -y gcc gcc-c++ make cmake automake autoconf libtool zlib-devel pcre-devel openssl-devel curl-devel libxml2-devel unzip zip bzip2-devel libxslt-devel gd-devel freetype-devel libjpeg-devel libpng-devel libXpm-devel libaio ncurses-devel diffutils iptables && touch /tmp/yum_installed

code=$?
error_control $code "必须的组件安装错误,请确保yum能够使用!"
else
echo "必须的组件已经安装，即将跳过安装"
echo "想重新安装，请删除/tmp/yum_installed文件"
fi

# 创建用户组
groupadd -g 1000 www
useradd -g 1000 -u 1000 -d /dev/null -s /sbin/nologin www > /dev/null 2>&1


mkdir -p /www $cur_dir/untar /www/server /www/mysql /www/web /www/myconf
cp -rf $cur_dir/myconf/* /www/myconf


touch /etc/ld.so.conf.d/lnmp.conf

# 复制iptables文件
cp -f /www/myconf/iptables /etc/sysconfig/iptables

# #add 80 port to iptables
# if [ -s /sbin/iptables ]; then
# /sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT
# /sbin/iptables-save
# fi
# }

service iptables restart

}


#安装nginx
function install_nginx(){
soft_version="nginx-1.4.4"
cd $cur_dir
if [ ! -d /www/server/nginx/sbin ];then
echo "================$soft_version install Start ================"

download_files $soft_version

tar zxvf $soft_version.tar.gz -C ./untar
cd untar/$soft_version

./configure --prefix=/www/server/nginx --user=www --group=www --with-http_stub_status_module --with-http_ssl_module 2>/root/oslamp_errors.log
code=$?
error_control $code $soft_version
parallel_make 2>/root/oslamp_errors.log
code=$?
error_control $code $soft_version
make install

# 添加服务
rm -rf /etc/init.d/nginx
cp -f /www/myconf/nginx /etc/init.d/nginx
chmod 755 /etc/init.d/nginx
chkconfig --add nginx
chkconfig nginx on

# 修改配置文件的参数
mkdir /www/server/nginx/conf/vhost /www/web/default
cp -rf /www/myconf/nginx.conf /www/server/nginx/conf/nginx.conf
cp -rf /www/myconf/php-error.conf  /www/server/nginx/conf/php-error.conf

cp -rf /www/myconf/errorpage  /www/web/
cp -rf /www/myconf/tz.php  /www/web/default/index.php

service nginx start

code=$?
error_control $code " nginx start error"

echo "======================nginx install completed========================"
else
echo "nginx已经安装过了，请卸载后安装，或者删除 /www/server/nginx 文件夹后再安装"

echo "等待5秒后继续安装"
sleep 5
fi
}


#安装mysql
function install_mysql(){

#如果不存在此目录 才进行安装
if [ ! -d /www/server/mysql/bin ];then

if [ $X64 == "1" ] ; then
	soft_version="mysql-5.5.36-linux2.6-x86_64"
else
	soft_version="mysql-5.5.36-linux2.6-i686"
fi

echo "============================$soft_version install============================================"

yum -y remove mysql-server mysql mysql-devel

cd $cur_dir/
download_files $soft_version
tar zxvf $soft_version.tar.gz -C ./untar

# 增加用户组
useradd -d /dev/null -s /sbin/nologin mysql > /dev/null 2>&1

mv $cur_dir/untar/$soft_version /www/server/mysql
chown -R mysql:mysql /www/server/mysql

# 复制配置文件
cp -f /www/server/mysql/support-files/my-medium.cnf /www/server/mysql/my.cnf
 # 初始化数据库
/www/server/mysql/scripts/mysql_install_db --defaults-file=/www/server/mysql/my.cnf --basedir=/www/server/mysql --datadir=/www/mysql --user=mysql

# 设置服务文件
rm -rf /etc/init.d/mysqld
cp -rf /www/server/mysql/support-files/mysql.server /etc/init.d/mysqld
sed -i "s:^basedir=.*:basedir=/www/server/mysql:g" /etc/init.d/mysqld
sed -i "s:^datadir=.*:datadir=/www/mysql:g" /etc/init.d/mysqld

chmod +x /etc/init.d/mysqld
chkconfig --add mysqld
chkconfig  mysqld on

# 设置类库路径
cat >> /etc/ld.so.conf.d/lnmp.conf<<EOF
/www/server/mysql/lib
EOF

rm -rf /usr/lib64/mysql /usr/lib/mysql
# 加载动态库
ldconfig

# 添加环境变量
ln -sf /www/server/mysql/bin/mysql /usr/bin
ln -sf /www/server/mysql/bin/mysqladmin /usr/bin

killall mysqld
rm -rf /etc/my.cnf

service mysqld start

code=$?
error_control $code " mysqld start error"
# 更改数据库密码
/www/server/mysql/bin/mysqladmin password $mysqlrootpwd

/www/server/mysql/bin/mysql -uroot -p$mysqlrootpwd <<EOF
drop database test;
delete from mysql.user where user='';
update mysql.user set password=password('$mysqlrootpwd') where user='root';
delete from mysql.user where not (user='root') ;
flush privileges;
exit
EOF

echo "============================$soft_version install completed  安装完成============================"

else
echo "mysql had been installed! 已经安装过了mysql,请删除 /www/server/mysql 文件夹后重新安装"

echo "等待5秒后继续安装"
sleep 5
fi
}

#安装类库文件
function install_lib(){
soft_version="libiconv-1.14"
cd $cur_dir/
download_files $soft_version
tar zxvf $soft_version.tar.gz -C ./untar
cd untar/$soft_version
./configure --prefix=/usr 2>/root/oslamp_errors.log
code=$?
error_control $code $soft_version
parallel_make 2>/root/oslamp_errors.log
code=$?
error_control $code $soft_version
make install


soft_version="libmcrypt-2.5.8"
cd $cur_dir/
download_files $soft_version
tar zxvf $soft_version.tar.gz -C ./untar
cd untar/$soft_version
./configure --prefix=/usr 2>/root/oslamp_errors.log
code=$?
error_control $code $soft_version
parallel_make 2>/root/oslamp_errors.log
code=$?
error_control $code $soft_version
make install


soft_version="mhash-0.9.9"
cd $cur_dir/
download_files $soft_version
tar zxvf $soft_version.tar.gz -C ./untar
cd untar/$soft_version
./configure --prefix=/usr 2>/root/oslamp_errors.log
code=$?
error_control $code $soft_version
parallel_make 2>/root/oslamp_errors.log
code=$?
error_control $code $soft_version
make install

# 64位版本
if [ $X64 == "1" ] ; then
	# ln -s /usr/lib/libiconv.* /usr/lib64/
	# ln -s /usr/lib/libmcrypt.* /usr/lib64/
	# ln -s /usr/lib/libmhash.* /usr/lib64/
	# 设置类库路径
	cat >> /etc/ld.so.conf.d/lnmp.conf<<EOF
/usr/lib
EOF
	# 加载动态库
	ldconfig
fi

soft_version="mcrypt-2.6.8"
cd $cur_dir/
download_files $soft_version
tar zxvf $soft_version.tar.gz -C ./untar
cd untar/$soft_version
./configure --prefix=/usr 2>/root/oslamp_errors.log
code=$?
error_control $code $soft_version
parallel_make 2>/root/oslamp_errors.log
code=$?
error_control $code $soft_version
make install

}

#安装php
function install_php(){
soft_version="php-5.4.24"
if [ ! -d /www/server/php ];then
echo "============================$soft_version install============================================"
cd $cur_dir/
download_files $soft_version
tar zxvf $soft_version.tar.gz -C ./untar
cd ./untar/$soft_version
./configure --prefix=/www/server/php --with-config-file-path=/www/server/php --with-config-file-scan-dir=/www/server/php/php.d --enable-fpm --with-fpm-user=www --with-fpm-group=www --with-openssl --with-zlib  --with-curl --enable-ftp --enable-sockets --with-mysql=mysqlnd --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --enable-pdo --enable-mbstring --without-pear --with-xmlrpc --enable-zip  --enable-xml --with-bz2 --with-xsl --enable-soap --with-gd --with-freetype-dir --with-jpeg-dir --with-png-dir  --enable-gd-native-ttf --with-gettext --enable-bcmath --with-mhash --with-mcrypt --with-iconv=/usr 2>/root/oslamp_errors.log

code=$?
error_control $code
parallel_make 2>/root/oslamp_errors.log
# ZEND_EXTRA_LIBS='-liconv'
code=$?
error_control $code
make install

#复制配置文件
cp -f php.ini-production /www/server/php/php.ini

rm -rf /etc/php.ini
sed -i 's/post_max_size = 8M/post_max_size = 50M/g' /www/server/php/php.ini
sed -i 's/upload_max_filesize = 2M/upload_max_filesize = 50M/g' /www/server/php/php.ini
sed -i 's/;date.timezone =/date.timezone = PRC/g' /www/server/php/php.ini
sed -i 's/short_open_tag = Off/short_open_tag = On/g' /www/server/php/php.ini
sed -i 's/; cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/g' /www/server/php/php.ini
sed -i 's/; cgi.fix_pathinfo=0/cgi.fix_pathinfo=0/g' /www/server/php/php.ini
sed -i 's/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/g' /www/server/php/php.ini
# sed -i 's/max_execution_time = 30/max_execution_time = 300/g' /www/server/php/php.ini
# sed -i 's/register_long_arrays = On/;register_long_arrays = On/g' /www/server/php/php.ini
# sed -i 's/magic_quotes_gpc = On/;magic_quotes_gpc = On/g' /www/server/php/php.ini
sed -i 's/disable_functions =.*/disable_functions = passthru,exec,system,chroot,scandir,chgrp,chown,shell_exec,proc_open,proc_get_status,ini_alter,ini_restore,dl,openlog,syslog,readlink,symlink,popepassthru,stream_socket_server/g' /www/server/php/php.ini


mkdir -p /www/server/php/php.d
if [ $X64 == "1" ] ; then
	cp -f /www/myconf/ZendGuardLoader-x64.so /www/server/php/php.d/ZendGuardLoader.so
else
	cp -f /www/myconf/ZendGuardLoader-x86.so /www/server/php/php.d/ZendGuardLoader.so
fi
echo "Write ZendGuardLoader to php.ini......"
cat > /www/server/php/php.d/ZendGuardLoader.ini<<EOF
[Zend Optimizer] 
zend_extension=/www/server/php/php.d/ZendGuardLoader.so
zend_loader.enable=1
zend_loader.disable_licensing=0
zend_loader.obfuscation_level_support=3

EOF

cp /www/server/php/etc/php-fpm.conf.default /www/server/php/etc/php-fpm.conf
# 设置服务
cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
chmod +x /etc/init.d/php-fpm
chkconfig --add php-fpm
chkconfig  php-fpm on

echo "============================$soft_version install completed============================================"
else
echo "PHP had been installed--php已经安装过了，请删除 /www/server/php 重新安装"

echo "等待5秒后继续安装"
sleep 5
fi
service php-fpm restart
}

#安装和配置postfix
function install_postfix(){
	
	echo "============================postfix install=================================================="
	rpm -e sendmail --nodeps
	yum -y remove sendmail
	
	yum install -y postfix
	cp -f $cur_dir/myconf/main.cf /etc/postfix/main.cf
	sed -i "s#{postfixdomain}#$postfixdomain#g" /etc/postfix/main.cf
	chkconfig postfix on
	service postfix restart
}

#安装pureftpd
function install_pureftpd() {
soft_version="pure-ftpd-1.0.36"
echo "============================pureftpd install ============================================"
rpm -e vsftpd
yum -y remove vsftpd

rpm -e pure-ftpd
yum -y remove pure-ftpd


cd $cur_dir
download_files $soft_version
tar zxvf $soft_version.tar.gz -C ./untar
cd ./untar/$soft_version/

./configure --prefix=/www/server/pureftpd --with-mysql=/www/server/mysql --with-quotas --with-cookie --with-virtualhosts --with-virtualchroot --with-diraliases --with-sysquotas --with-ratios --with-altlog --with-paranoidmsg --with-shadow --with-welcomemsg  --with-throttling --with-uploadscript --with-language=simplified-chinese --with-rfc2640
code=$?
error_control $code
parallel_make 2>/root/lamp_errors.log
code=$?
error_control $code
make install
# 添加 环境变量
ln -sf /www/server/pureftpd/sbin/pure-ftpd /usr/sbin/
# 添加服务
cp -f /www/myconf/pure-ftpd /etc/init.d/pure-ftpd
cp -f configuration-file/pure-config.pl /www/server/pureftpd/sbin/pure-config.pl
chmod 755 /etc/init.d/pure-ftpd
chmod 755 /www/server/pureftpd/sbin/pure-config.pl
chkconfig --add pure-ftpd
chkconfig pure-ftpd on


# 更改pure-mysql密码
sed -i "s/{passwd}/$mysqlrootpwd/g" /www/myconf/pureftpd-mysql.conf

sed -i "s/{passwd}/$mysqlrootpwd/g" /www/myconf/pure-ftpd.sql


# 增加配置文件
cp -f /www/myconf/pure-ftpd.conf /www/server/pureftpd/pure-ftpd.conf
cp -f /www/myconf/pureftpd-mysql.conf /www/server/pureftpd/pureftpd-mysql.conf


/www/server/mysql/bin/mysql -uroot -p$mysqlrootpwd < /www/myconf/pure-ftpd.sql

code=$?
error_control $code

echo 'IPTABLES_MODULES="ip_conntrack_ftp"' >>/etc/sysconfig/iptables-config
/etc/init.d/iptables restart

if [[ -f /etc/syslog.conf ]];then
	touch /www/server/pureftpd/pureftpd.log
	sed -i 's/cron.none/cron.none;ftp.none/g' /etc/syslog.conf
	echo 'ftp.*        -/www/server/pureftpd/pureftpd.log' >> /etc/syslog.conf
	/etc/init.d/syslog restart
fi
# 开启服务
service pure-ftpd start
echo "============================pureftpd install completed============================================"	
}


#安装phpmyadmin
function install_phpmyadmin(){
	soft_version="phpmyadmin"
	echo "============================phpmyadmin install=================================================="
	
	cd $cur_dir
	download_files $soft_version
	tar zxvf $soft_version.tar.gz -C /www/web
	
	cp -f /www/myconf/phpmyadmin.conf /www/server/nginx/conf/vhost/phpmyadmin.conf
	service nginx restart
}


###############################################################################
#安装lamp 程序
function install_all(){

#安装前的配置
pre_installation_settings
#安装apache
install_nginx
#安装mysql
install_mysql

install_lib
install_php

# install_postfix

install_pureftpd

install_phpmyadmin

chown -R www.www /www/web
#添加系统环境变量
\cp -f $cur_dir/lnmp.sh /usr/bin/lnmp

# rm -rf $cur_dir/untar/*
echo "============================lnmp install completed============================================"
echo "mysql root password--数据库root密码:$mysqlrootpwd"
echo "default web root--默认网站路径:/www/web/default"
echo "default mysqldata root--默认数据保存路径:/www/mysql"

Domain=`ifconfig  | grep 'inet addr:'| grep -v '127.0.0.*' | cut -d: -f2 | awk '{ print $1}'`;
echo "Your admin url information--phpmyadmin访问路径:http://${Domain}:8080"

echo "For more information--更多信息请访问:www.baidu.com"
echo "============================lnmp install completed============================================"
exit 0
}
#卸载oslamp

function uninstall_all(){
echo "will uninstall lnmp--将要卸载lnmp管理系统"
sleep 2
killall nginx
killall mysqld
killall pure-ftpd
rm -rf /www/server /etc/init.d/nginx /var/lock/subsys/httpd /var/spool/mail/nginx /etc/logrotate.d/nginx
rm -rf /etc/init.d/mysqld /etc/ld.so.conf.d/mysql.conf /usr/bin/mysql /var/lock/subsys/mysql /var/spool/mail/mysql

rm -rf /etc/init.d/pure-ftpd /usr/sbin/pure-ftpd
rm -rf /root/lnmp /usr/bin/lnmp
echo "successfully uninstall lnmp -- lnmp卸载成功"
echo "所有数据保存在 /www"
exit 0
}


################################################################################
#安装开始的地方																   #
################################################################################
#判断输入的参数 不是--help 则执行下面的内容
if [ "$1" == "--help" ]; then
	echo "帮助文档还没有写好"
	exit 1
fi

#开始安装前的准备
clear
echo "========================================================================="
echo "lnmp V1.0.1 for CentOS/RadHat Linux VPS  Written by bjdgyc"
echo "========================================================================="
echo "开源lnmp 安装程序是一个方便LINUX站点管理的后台系统"
echo "========================================================================="
echo "For more information please visit http://www.baidu.com"
echo "========================================================================="

echo "Press any key to start...--请安任意键继续"
char=`get_char`
#安装或者卸载oslamp
#1-Select Install lnmp
echo "Select Install lnmp--选择安装 或者卸载WEB服务系统:"
echo "y Install webserver--安装WEB服务系统"
echo "n Donot Install webserver--卸载WEB服务系统"
while true
do
read -p "Please Input y,n--请输入y或者n: " all
case $all in
y|Y|YES|yes|Yes)
all=y
break
;;
n|N|no|NO|No)
all=n
break
;;
*) echo Please enter only y or n
esac
done

#开始执行
if [ "$all" != "n" ]; then
install_all
else
uninstall_all
fi
